import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: false,
    user: null,
    registeredUsers: []
  }),
  
  actions: {
    // 注册新用户
    register(userData) {
      // 检查用户名是否已存在
      const userExists = this.registeredUsers.some(
        user => user.username === userData.username
      );
      
      if (userExists) {
        throw new Error('用户名已存在');
      }
      
      // 添加新用户
      this.registeredUsers.push({
        ...userData,
        id: Date.now().toString()
      });
      
      console.log('已注册用户:', this.registeredUsers);
    },
    
    // 用户登录
    login(credentials) {
      const user = this.registeredUsers.find(
        user => 
          user.username === credentials.username && 
          user.password === credentials.password
      );
      
      if (user) {
        this.isLoggedIn = true;
        this.user = {
          username: user.username,
          email: user.email,
          gender: user.gender,
          job: user.job,
          id: user.id
        };
        return true;
      } else {
        throw new Error('用户名或密码错误');
      }
    },
    
    // 用户登出
    logout() {
      this.isLoggedIn = false;
      this.user = null;
    }
  },
  
  // 持久化存储（使用pinia-plugin-persistedstate）
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user-store',
        storage: localStorage
      }
    ]
  }
});